package com.boot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;


/**
 * Created by Wuxiang on 2017/7/28.
 * @EnableWebSecurity注解 开启Spring Security的功能
 *
 * 访问http://localhost:8080/，可以正常访问
 * 访问http://localhost:8080/hello的时候被重定向到了http://localhost:8080/login页面
 * 输入用户名user和密码password进行登录后，跳转到了Hello World页面
 *  http://localhost:8080/login?logout  注销
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 通过authorizeRequests()定义哪些URL需要被保护、哪些不需要被保护
     * formLogin()定义当需要用户登录时候，转到的登录页面
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

    /**
     * configureGlobal(AuthenticationManagerBuilder auth)方法，
     * 在内存中创建了一个用户，该用户的名称为user，密码为password，用户角色为USER
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}
